package com.cn.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.cn.dto.SkuAddCartDTO;
import com.cn.entity.ShoppingCart;
import com.cn.vo.ShoppingCartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShoppingCartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String SHOP_CART_SKU = "SHOP_CART:SKU:";
    private static final String SHOP_CART_INFO = "SHOP_CART:INFO:";
    private static final String SHOP_CART_COUNT = "SHOP_CART:COUNT:";
    private static final String SHOP_CART_SHOP_ID = "SHOP_CART:SHOP_ID:";
    private static final String GOODS_SKU = "GOODS_SKU:";


    //查询购物车接口,伪代码
    public LinkedHashMap<String, List<ShoppingCart>> queryShoppingCartList(Long userId, Integer page, Integer pageNum) {

        //获取商店id，可以根据start和end进行分页
        Set shopIdSet = stringRedisTemplate.opsForZSet().reverseRange(SHOP_CART_SHOP_ID + userId, 0, -1);
        //使用商店id获取购物车里面对应的商品
        List<Object> k = stringRedisTemplate.opsForHash().multiGet(SHOP_CART_SKU + userId, shopIdSet);
        //转换出所有的商品sku
        List skus = new ArrayList<>();
        k.forEach(x -> {
            Set<String> skuIds = JSON.parseObject(x.toString(), Set.class);
            skus.addAll(skuIds);
        });
        //使用商品sku获取对应的商品信息
        List<Object> list1 = stringRedisTemplate.opsForHash().multiGet(SHOP_CART_INFO + userId, skus);
        //转换成商店包含商品的结构数据
        LinkedHashMap<String, List<ShoppingCart>> shopCartList = new LinkedHashMap<>();
        String o = null;
        for (int i = 0; i < list1.size(); i++) {
            o = list1.get(i).toString();
            ShoppingCart shopCart = JSON.parseObject(o, ShoppingCart.class);
            String shopId = shopCart.getShopId().toString();
            if (!shopCartList.containsKey(shopId)) {
                shopCartList.put(shopId, new ArrayList<>());
            }
            List<ShoppingCart> cartList = shopCartList.get(shopId);
            cartList.add(shopCart);
        }

        return shopCartList;
    }

    //添加购物车
    public Boolean addShoppingCart(SkuAddCartDTO skuAddCart) {
        Long userId = skuAddCart.getUserId();
        //根据skuId查询出商品信息和SKU信息，然后放进购物车中保存 @todo 伪代码
        String skuId = skuAddCart.getSkuId().toString();
        Long num = (Long) redisTemplate.opsForValue().get(GOODS_SKU + skuId);
        //判断份额是否充足
        if (num > skuAddCart.getAmount()) {
            String shopId = skuAddCart.getShopId().toString();
            //购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtil.copyProperties(skuAddCart, shoppingCart);
            //价钱是在上面查询出来,写死价格 @todo 伪代码
            shoppingCart.setMoney(998L);
            //添加-商店id，更新商品的向上移动一位
            stringRedisTemplate.opsForZSet().incrementScore(SHOP_CART_SHOP_ID + userId, shopId, 1);
            //更加
            String skus = (String) stringRedisTemplate.opsForHash().get(SHOP_CART_SKU + userId, shopId);
            Set<String> skuList = (skus == null ? new HashSet<>() : JSON.parseObject(skus, Set.class));

            if (!skuList.contains(skuId)) {
                skuList.add(skuId);
                stringRedisTemplate.opsForHash().put(SHOP_CART_SKU + userId, shopId, JSON.toJSONString(skuList));
            }
            //设置商品数量
            stringRedisTemplate.opsForHash().put(SHOP_CART_COUNT + userId, skuId, skuAddCart.getAmount().toString());
            //把对象返回，异步添加进购物车类表 @todo 发MQ
            stringRedisTemplate.opsForHash().put(SHOP_CART_INFO + userId, skuId, JSON.toJSONString(shoppingCart));

            return true;
        }


//        stringRedisTemplate.opsForZSet().add(SHOP_CART_SKU + userId, skuId, 1);
        return false;
    }

    //增加商品数量
    public Boolean addShoppingCartGoods(SkuAddCartDTO skuAddCart) {
        String skuId = skuAddCart.getSkuId().toString();
        Integer amount = skuAddCart.getAmount();
        Long userId = skuAddCart.getUserId();
        String shopId = skuAddCart.getShopId().toString();
        //判断商品数量是否充足
//        Long num = (Long) redisTemplate.opsForValue().get(GOODS_SKU + skuId);
        Long num = stringRedisTemplate.opsForHash().increment(GOODS_SKU , skuId,0);
        Long total = stringRedisTemplate.opsForHash().increment(SHOP_CART_COUNT + userId, skuId, 0);
        if (num >= (amount + total)) {
            //更新购物车商品数量
            Long newTotal = stringRedisTemplate.opsForHash().increment(SHOP_CART_COUNT + userId, skuId, amount);

            //发送MQ去更新info数据,模拟流程而已
            String json = (String) stringRedisTemplate.opsForHash().get(SHOP_CART_INFO + userId, skuId);
            ShoppingCart shoppingCart = JSON.parseObject(json, ShoppingCart.class);
            shoppingCart.setAmount(total.intValue());
            //修改购物车类表商品的持久数据
            stringRedisTemplate.opsForHash().put(SHOP_CART_INFO + userId, skuId, JSON.toJSONString(shoppingCart));
            //数据位移1
            stringRedisTemplate.opsForZSet().incrementScore(SHOP_CART_SHOP_ID + userId, shopId, 1);

        }
        return true;
    }

    //减少商品数量

    //删除商品

    //购物车全选商品

    //根据商店勾选商品

    //单个勾选商品

    //结算，选择商品预生成订单

    //提交订单

    //支付

}
